package websphinx;

public class MatchStartRepeat implements MatchAction {
	private String name = null;

	public MatchStartRepeat(String name) {
		this.name = name;
	}

	@Override
	public boolean match(Matcher matcher) {
		if (matcher.actionSucc) {
			int index = matcher.getMatchActions().indexOf(this);
			matcher.repeats.add(index);
			matcher.repeatTimes.add(0);
		} else {
			int count = 1;
			int index = matcher.getMatchActions().indexOf(this) + 1;
			for (; index < matcher.getMatchActions().size(); index++) {
				if (matcher.getMatchActions().elementAt(index) instanceof MatchStartRepeat)
					count++;
				else if (matcher.getMatchActions().elementAt(index) instanceof MatchCloseRepeat)
					count--;

				if (count == 0)
					break;
			}
			matcher.nextAction = index;

			matcher.repeats.remove(matcher.repeats.size() - 1);
			matcher.repeatTimes.remove(matcher.repeatTimes.size() - 1);
		}

		return true;
	}

	@Override
	public boolean apply(Matcher matcher) {
		if (matcher.actionSucc) {
			int index = matcher.getApplyActions().indexOf(this);
			matcher.repeats.add(index);
			matcher.repeatTimes.add(0);
		} else {
			int count = 1;
			int index = matcher.getApplyActions().indexOf(this) + 1;
			for (; index > 0; index++) {
				if (matcher.getApplyActions().elementAt(index) instanceof MatchStartRepeat)
					count++;
				else if (matcher.getApplyActions().elementAt(index) instanceof MatchCloseRepeat)
					count--;

				if (count == 0)
					break;
			}
			matcher.nextAction = index;

			matcher.repeats.remove(matcher.repeats.size() - 1);
			matcher.repeatTimes.remove(matcher.repeatTimes.size() - 1);
		}

		return true;
	}

}
